/**
 * LiquidGearAppDelegate.m by Giraldo Rosales.
 * Visit www.liquidgear.net for documentation and updates.
 *
 *
 * Copyright (c) 2009 Nitrogen Design, Inc. All rights reserved.
 * 
 * Permission is hereby granted, free of charge, to any person
 * obtaining a copy of this software and associated documentation
 * files (the "Software"), to deal in the Software without
 * restriction, including without limitation the rights to use,
 * copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the
 * Software is furnished to do so, subject to the following
 * conditions:
 * 
 * The above copyright notice and this permission notice shall be
 * included in all copies or substantial portions of the Software.
 * 
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
 * OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
 * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
 * HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
 * WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
 * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
 * OTHER DEALINGS IN THE SOFTWARE.
 **/

#import "LiquidGearAppDelegate.h"
#import "Utils.h"
#import "WebController.h"

#if LG_USE_ADMOB
#import "AdMob.h"
#endif

#if LG_USE_NAVBAR
#import "NavBar.h"
#endif

#if LG_USE_SOUND
#import "Sound.h"
#endif

#if LG_USE_TABBAR
#import "TabBar.h"
#endif

@implementation LiquidGearAppDelegate

@synthesize currentRect, idleMax, idleTimer, splash, viewController, window;

#if LG_USE_ADMOB
@synthesize admob, useAdMob;
#endif

#if LG_USE_NAVBAR
@synthesize navigation;
#endif

#if LG_USE_SOUND
@synthesize sound;
#endif

#if LG_USE_TABBAR
@synthesize tabs, useTabBar;
#endif

- (void)applicationDidFinishLaunching:(UIApplication *)application {
	NSLog(@"Initialized.");
	
	NSBundle *mainBundle = [NSBundle bundleForClass:[self class]];
	
	//Events
	self.applicationSupportsShakeToEdit	= LG_EVENT_SHAKEEDIT;
	
	//Idle
	self.idleTimerDisabled	= LG_IDLE;
	idleTimer	= [[NSTimer alloc] init];
	idleMax		= LG_IDLE_TIME;
	
#if LG_USE_SOUND
	if([LG_SFX_STARTUP length] > 0) {
		[[[Sound alloc] autorelease] play:LG_SFX_STARTUP];
	}
#endif
	
	NSURL *appURL;
	appURL = [[NSURL fileURLWithPath:[mainBundle pathForResource:@"index" ofType:@"html" inDirectory:@"www"]] retain];
	
	[application setStatusBarStyle:UIStatusBarStyleBlackTranslucent animated:TRUE];
	
	CGRect winRect	= [[UIScreen mainScreen] applicationFrame];
	
	window = [[UIWindow alloc] initWithFrame:winRect];
	
	//Add WebView
	viewController = [[WebController alloc] init:CGRectMake(0, 0, winRect.size.width, winRect.size.height)];
	[viewController setAppURL:appURL];
	[viewController.webView setScalesPageToFit:LG_SCALE_TO_FIT];
	
	currentRect	= viewController.webView.frame;
	
#if LG_USE_NAVBAR
	//Add Navigation Bar
	navigation	= [[NavBar alloc] initWithController:viewController];
	viewController.navBar	= navigation;
	[window addSubview:(UINavigationBar*)navigation.navBar];
#endif
	
#if LG_USE_TABBAR
	//Add Tab Bar
	useTabBar	= FALSE;
	tabs			= [[TabBar alloc] initWithController:viewController];
	viewController.tabs	= tabs;
	[window addSubview:(UITabBar*)tabs.tabBar];
#endif

#if LG_USE_ADMOB
	//Add AdMob banner
	useAdMob	= FALSE;
	admob			= [[AdMob alloc] initWithController:viewController];
	viewController.admob	= admob;
	[window addSubview:admob.view];
#endif
	
	[window addSubview:viewController.view];
	[window makeKeyAndVisible];
	
	//Splash Screen
	CGRect splashRect;
	if(application.statusBarHidden) {
		splashRect	= CGRectMake(0, 0, winRect.size.width, winRect.size.height);
	} else {
		splashRect	= CGRectMake(0, -20, winRect.size.width, winRect.size.height+20);
	}
	
	splash								= [[SplashView alloc] initWithFrame:splashRect];
	splash.animation			= SplashViewAnimationFade;
	splash.animationDelay	= 0;
	splash.delay					= .5;
	splash.touchAllowed		= NO;
	splash.delegate				= self;
	[window addSubview:splash];
	[splash startSplash];
	[splash release];
}

- (void)applicationDidBecomeActive:(UIApplication *)application {
	NSLog(@"applicationDidBecomeActive");
}

- (void)applicationWillResignActive:(UIApplication *)application {
	NSLog(@"applicationWillResignActive");
}

- (void)sendEvent:(UIEvent *)event {
	NSSet *touches			= [event allTouches];
	
	BOOL forwardToSuper	= YES;
	BOOL isDouble				= NO;
	
	if (viewController.webView != nil) {
		for (UITouch *touch in touches) {
			if(touch.phase == UITouchPhaseBegan) {
				NSDictionary *touchBeginCall	= [NSDictionary dictionaryWithObjectsAndKeys:
																				 @"lg_touch_begin", @"event",
																				 [NSString stringWithFormat:@"%f", [touch locationInView:viewController.webView].x], @"x",
																				 [NSString stringWithFormat:@"%f", [touch locationInView:viewController.webView].y], @"y",
																				 nil
																				 ];
				//[[[Utils alloc] autorelease] jsCall:viewController.webView type:@"application" data:touchBeginCall directCall:nil];
			}
			else if(touch.phase == UITouchPhaseEnded) {
				NSDictionary *touchEndCall	= [NSDictionary dictionaryWithObjectsAndKeys:
																				 @"lg_touch_end", @"event",
																				 [NSString stringWithFormat:@"%f", [touch locationInView:viewController.webView].x], @"x",
																				 [NSString stringWithFormat:@"%f", [touch locationInView:viewController.webView].y], @"y",
																				 nil
																				 ];
				//[[[Utils alloc] autorelease] jsCall:viewController.webView type:@"touch" data:touchEndCall directCall:nil];
				
				if ([touch tapCount] == 2) {
					NSLog(@"Double Clicked");
					forwardToSuper	= LG_EVENT_DOUBLE;
					isDouble				= YES;
				}
			}
		}
	}
	
	if (forwardToSuper){
		[super sendEvent:event];
	}
	
	//Double Click
	if(isDouble) {
		NSDictionary *callback	= [NSDictionary dictionaryWithObject:@"lg_click_double" forKey:@"event"];
		[[[Utils alloc] autorelease] jsCall:viewController.webView type:@"touch" data:callback directCall:nil];
	}
	
	//Set Custom Idle
	if(LG_IDLE_CUSTOM) {
		//Only want to reset the timer on a Began touch or an Ended touch, to reduce the number of timer resets.
		if ([touches count] > 0) {
			//Touches count only ever seems to be 1, so anyObject works here.
			UITouchPhase phase = ((UITouch *)[touches anyObject]).phase;
			
			if (phase == UITouchPhaseBegan || phase == UITouchPhaseEnded) {
				[self resetIdleTimer];
			}
		}
	}
}

- (void)resetIdleTimer {
	if (idleTimer) {
		[idleTimer invalidate];
		[idleTimer release];
	}
	
	idleTimer = [[NSTimer scheduledTimerWithTimeInterval:idleMax target:self selector:@selector(idleTimerExceeded) userInfo:nil repeats:NO] retain];
}

- (void)idleTimerExceeded {
	NSLog(@"Idle time exceeded");
	NSDictionary *callback	= [NSDictionary dictionaryWithObject:@"lg_idle" forKey:@"event"];
	[[[Utils alloc] autorelease] jsCall:viewController.webView type:@"application" data:callback directCall:nil];
}


#ifdef __IPHONE_3_0
//Dispatch Touch Events
- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {
	
	for (UITouch *touch in touches) {
	//	NSLog(@"locationInView: x:%f y:%f", [touch locationInView:viewController.webView].x, [touch locationInView:viewController.webView].y);
	}
}

//Dispatch Shake Event
- (void)motionBegan:(UIEventSubtype)UIEventSubtypeMotionShake withEvent:(UIEvent *)event {
	NSDictionary *callback	= [NSDictionary dictionaryWithObject:@"lg_shake_start" forKey:@"event"];
	[[[Utils alloc] autorelease] jsCall:viewController.webView type:@"touch" data:callback directCall:nil];
}
- (void)motionEnded:(UIEventSubtype)UIEventSubtypeMotionShake withEvent:(UIEvent *)event {
	NSDictionary *callback	= [NSDictionary dictionaryWithObject:@"lg_shake_end" forKey:@"event"];
	[[[Utils alloc] autorelease] jsCall:viewController.webView type:@"touch" data:callback directCall:nil];
}
#endif

- (void)dealloc {
#if LG_USE_ADMOB
	[admob release];
#endif
	
#if LG_USE_NAVBAR
	[navigation release];
#endif
	
#if LG_USE_SOUND
	[sound release];
#endif
	
#if LG_USE_TABBAR
	[tabs release];
#endif
	
	[viewController release];
	[window release];
	[super dealloc];
}

@end